package t20250320.Wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.HeartbeatManagerOptions;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
import org.apache.flink.streaming.api.graph.JSONGenerator;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Arrays;

public class Wc1 {

    public static void main(String[] args) throws Exception {

        Configuration flinkConf = new Configuration();
        flinkConf.setString("rest.port","9091");
        flinkConf.setLong(HeartbeatManagerOptions.HEARTBEAT_TIMEOUT.key(), 3600 * 1000);
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(flinkConf);
        env.setParallelism(2);
        env.disableOperatorChaining();

        env.enableCheckpointing(1000, CheckpointingMode.EXACTLY_ONCE);

        DataStreamSource<String> source = env.addSource(new RichSourceFunction<String>() {

            private boolean isRunning = true;
            @Override
            public void run(SourceContext<String> ctx) throws Exception {
                while (isRunning) {
                    ctx.collect("hello,world");
                    Thread.sleep(1000);
                }
            }

            @Override
            public void cancel() {
                isRunning = false;
            }
        });


        SingleOutputStreamOperator<Tuple2<String, Integer>> ssos = source.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                for (String s : value.split(",")) {
                    out.collect(new Tuple2<String, Integer>(s, 1));
                }
            }
        });

        ssos.keyBy(value -> value.f0)
                .sum(1)
                .print();

        StreamGraph streamGraph = env.getStreamGraph(false);
        String streamingPlanAsJSON = streamGraph.getStreamingPlanAsJSON();
        System.out.println(streamingPlanAsJSON);

        env.execute("app");





    }
}
